package com.lagou.cluster.controller;

import com.lagou.cluster.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName LoginController
 * @Description 登录controller
 * @Author playboy
 * @Date 2021/5/25 6:52 下午
 * @Version 1.0
 **/
@Controller
@RequestMapping
public class LoginController {
	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private LoginService loginService;

	/**
	 * 跳转到登录页面
	 *
	 * @return
	 */
	@RequestMapping("/toLogin")
	public String toLogin(HttpServletRequest request, Model model) {
		model.addAttribute("loginPath", request.getContextPath() + "/login");
		return "login";
	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request, Model model, HttpSession session) {
		String contextPath = request.getServletContext().getContextPath();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//查询数据库，获取密码
		boolean login = loginService.login(username, password);
		if (login) {
			//相同，登录成功，写入session,重定向到index.html
			session.setAttribute("username", username);
			return "redirect:/index";
		} else {
			//不相同，重定向到login.html
			return "redirect:/toLogin";
		}
	}

}
